<template>
  <div id="admin">
    <div class="admin-title">
      <div>管理员管理</div>
      <div class="button" style="margin-right: 20px">
        <el-button type="primary" @click="getRoleData()">新增管理员</el-button>
      </div>
    </div>
    <div class="admin-table">
      <div class="admin-button">
        <div class="input">
          <!-- <div class="seach">
            <el-input placeholder="请输入内容" v-model="input" clearable>
            </el-input>
            <el-button type="primary" icon="el-icon-search"></el-button>
          </div> -->
        </div>
      </div>
      <div class="tabel">
        <el-table
          :data="tableData"
          border
          style="width: 100%"
          height="calc(100vh - 356px)"
        >
          <el-table-column
            type="index"
            width="50"
            fixed
            align="center"
            label="序号"
          >
          </el-table-column>
          <el-table-column prop="name" label="姓名" width="120" align="center">
          </el-table-column>
          <el-table-column label="角色身份" width="280" align="center">
            <template slot-scope="scope">
              <div class="el-table_1_column_3">
                <div
                  id="text"
                  v-for="(item, index) in scope.row.roles"
                  :key="index"
                >
                  {{ item.rolename }}
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            prop="username"
            label="账号"
            width="200"
            align="center"
          >
          </el-table-column>
          <el-table-column
            prop="phone"
            label="手机号"
            width="120"
            align="center"
          >
          </el-table-column>
          <el-table-column
            prop="email"
            label="电子邮箱"
            width="250"
            align="center"
          >
          </el-table-column>
          <el-table-column prop="remark" label="备注" align="center">
          </el-table-column>
          <el-table-column
            fixed="right"
            label="操作"
            width="130px"
            align="center"
          >
            <template slot-scope="scope">
              <el-button
                @click="handleClick(scope.row)"
                type="primary"
                icon="el-icon-edit"
                circle
                size="small"
              ></el-button>
              <el-button
                @click="deleteManager(scope.row)"
                size="small"
                type="danger"
                icon="el-icon-delete"
                circle
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <div class="admin-page">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageData.page"
        :page-sizes="[10, 20, 30, 40, 50]"
        :page-size="pageData.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="this.managerDataLength.length"
      >
      </el-pagination>
    </div>

    <!-- form表单 -->
    <el-dialog
      :title="isAdd ? '新增用户' : '修改用户信息'"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleClose"
      :close-on-click-modal="false"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="账号" prop="username">
          <el-input v-model="form.username" clearable></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="isAdd">
          <el-input
            v-model="form.password"
            show-password
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <!-- <el-form-item label="修改密码" prop="password" v-else>
          <el-input
            v-model="form.password"
            show-password
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="checkPass">
          <el-input
            v-model="form.checkPass"
            show-password
            autocomplete="off"
          ></el-input>
        </el-form-item> -->
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" clearable></el-input>
        </el-form-item>
        <el-form-item label="角色身份" prop="region">
          <el-select
            v-model="form.role"
            multiple
            default-first-option
            placeholder="请选择角色标签"
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="form.phone" clearable></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" clearable></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input type="textarea" v-model="form.remark"></el-input>
        </el-form-item>
      </el-form>

      <!-- 内层dialog -->
      <el-dialog
        width="30%"
        title="修改密码"
        :visible.sync="innerVisible"
        append-to-body
        center
      >
        <el-form ref="form" :model="form" :rules="rules" label-width="80px"
          ><el-form-item label="修改密码" prop="password">
            <el-input
              v-model="form.password"
              show-password
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item label="确认密码" prop="checkPass">
            <el-input
              v-model="form.checkPass"
              show-password
              autocomplete="off"
            ></el-input> </el-form-item
        ></el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="resetFormPassword('form')">取 消</el-button>
          <el-button type="primary" @click="onSubmitPassword('form', form)"
            >确 定</el-button
          >
        </span>
      </el-dialog>
      <span slot="footer" class="dialog-footer-left" v-if="isAdd == false">
        <el-button @click="innerVisible = true">修改密码</el-button></span
      >
      <span slot="footer" class="dialog-footer">
        <el-button @click="resetForm('form')">取 消</el-button>
        <el-button type="primary" @click="onSubmit('form', form)"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  manager,
  deleteManager,
  updateManagers,
  getManager,
  getManagers,
} from "@/api/administrator";
import { getRoleList } from "@/api/role";

export default {
  data() {
    var validatePass = (rule, value, text) => {
      const regRole =
        /^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\W_!@#$%^&*`~()-+=]+$)(?![a-z0-9]+$)(?![a-z\W_!@#$%^&*`~()-+=]+$)(?![0-9\W_!@#$%^&*`~()-+=]+$)[a-zA-Z0-9\W_!@#$%^&*`~()-+=]/;
      if (regRole.test(value)) {
        return text();
      }
      text(
        new Error(
          "密码必须报含大写字母、小写字母、数字、特殊字符的任意三项组合"
        )
      );
    };
    var updatevalidatePass = (rule, value, text) => {
      const regRole =
        /^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\W_!@#$%^&*`~()-+=]+$)(?![a-z0-9]+$)(?![a-z\W_!@#$%^&*`~()-+=]+$)(?![0-9\W_!@#$%^&*`~()-+=]+$)[a-zA-Z0-9\W_!@#$%^&*`~()-+=]/;
      if (regRole.test(value)) {
        return text();
      } else if (value === "") {
        text(new Error("请再次输入密码"));
      } else {
        text(
          new Error(
            "密码必须报含大写字母、小写字母、数字、特殊字符的任意三项组合"
          )
        );
      }
    };
    var validatePass2 = (rule, value, text) => {
      if (value === "") {
        text(new Error("请再次输入密码"));
      } else if (value !== this.form.password) {
        text(new Error("两次输入密码不一致!"));
      } else {
        text();
      }
    };

    var checkEmail = (rules, value, text) => {
      const regRole =
        /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
      if (regRole.test(value)) {
        return text();
      }
      text(new Error("请输入正确邮箱"));
    };
    var checkPhoneNumber = (rules, value, text) => {
      const regRole = /^(?:(?:\+|00)86)?1\d{10}$/;
      if (regRole.test(value)) {
        return text();
      }
      text(new Error("请输入正确的电话号码"));
    };
    return {
      tableData: [],
      input: "",
      // form表单
      form: {
        name: "",
        username: "",
        password: "",
        checkPass: "",
        phone: "",
        email: "",
        remark: "",
        role: [],
      },
      rules: {
        username: [
          { required: true, message: "请输入活动名称", trigger: "blur" },
        ],
        password: [
          {
            required: true,
            message: "请输入密码",
            trigger: ["blur", "change"],
          },
          { validator: validatePass, trigger: "blur" },
        ],
        // password2: [
        //   // {
        //   //   message: "请输入密码",
        //   //   trigger: ["blur", "change"],
        //   // },
        //   { validator: updatevalidatePass, trigger: "blur" },
        // ],
        checkPass: [{ validator: validatePass2, trigger: "blur" }],

        name: [
          {
            required: true,
            message: "请输入你的真实姓名",
            trigger: "blur",
          },
          // { validator: checkName, trigger: "blur" },
        ],
        phone: [
          {
            required: true,
            message: "请输入电话号码",
            trigger: "blur",
          },
          { validator: checkPhoneNumber, trigger: "blur" },
        ],
        email: [
          {
            required: true,
            message: "请输入邮箱",
            trigger: "blur",
          },
          { validator: checkEmail, trigger: "blur" },
        ],
      },
      //弹窗
      dialogVisible: false,
      innerVisible: false,

      isAdd: true,

      options: [],

      pageData: {
        page: 1,
        size: 10,
        key: "",
      },
      managerDataLength: [],
    };
  },

  created() {
    this.init();
  },
  methods: {
    //初始化
    init() {
      this.getManagersData();
      this.getManagers();
      this.getRoleList();
    },

    getManagers() {
      getManagers().then((res) => {
        this.managerDataLength = res.data;
      });
    },

    //获取管理员信息
    getManagersData() {
      let data = {
        size: this.pageData.size,
        page: this.pageData.page,
      };
      getManager(data).then((res) => {
        this.tableData = res.data.data;
      });
    },

    //获取角色信息
    getRoleList() {
      getRoleList().then((res) => {
        res.data.forEach((element, index) => {
          let role = {
            value: element.id,
            label: element.rolename,
          };
          this.options.push(role);
        });
      });
    },

    handleClick(row) {
      this.isAdd = false;
      this.dialogVisible = true;
      this.form = Object.assign({}, row);
      // this.getRoleData();
    },

    handleSizeChange(val) {
      this.pageData.size = val;
      this.init();
    },

    handleCurrentChange(val) {
      this.pageData.page = val;
      this.init(); // return;
    },

    //表达提交按钮
    onSubmit(form, data) {
      this.$refs[form].validate((valid) => {
        if (valid) {
          if (this.isAdd) {
            manager(data).then((res) => {
              if (res.code == 0) {
                this.dialogVisible = false;
                this.$message({
                  type: "success",
                  message: res.data,
                });
                this.init();
              }
            });
          } else {
            updateManagers(data).then((res) => {
              if (res.code == 0) {
                this.dialogVisible = false;
                this.$message({
                  type: "success",
                  message: res.data,
                });
                this.init();
              }
            });
          }
        } else {
          return false;
        }
      });
    },

    //修改密码
    onSubmitPassword(form, data) {
      this.$refs[form].validate((valid) => {
        if (valid) {
          updateManagers(data).then((res) => {
            if (res.code == 0) {
              this.innerVisible = false;
              this.$message({
                type: "success",
                message: "修改密码成功",
              });
            }
          });
        } else {
          return false;
        }
      });
    },

    // 重置按钮
    resetForm(form) {
      this.$refs[form].resetFields();
      this.dialogVisible = false;
    },

    resetFormPassword(form) {
      this.$refs[form].resetFields();
      this.innerVisible = false;
    },

    //获取管理员身份
    getRoleData() {
      this.form = {};
      this.dialogVisible = true;
      this.isAdd = true;
    },

    //删除管理员
    deleteManager(row) {
      const h = this.$createElement;
      this.$msgbox({
        title: "提示",
        message: h("p", null, [
          h("span", null, "此操作将永久删除管理者 "),
          h("i", { style: "color: teal" }, row.name),
          h("span", null, "，是否继续？"),
        ]),
        showCancelButton: true,
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          deleteManager(row).then((res) => {
            if (res.code == 0) {
              this.$message({
                type: "success",
                message: res.data,
              });
              this.init();
            } else {
              this.$message({
                type: "danger",
                message: "发生错误无法删除",
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    handleClose(done) {
      this.$confirm("你还未提交信息，确认关闭？")
        .then((_) => {
          done();
          this.$refs.form.resetFields();
        })
        .catch((_) => {});
    },
  },
};
</script>

<style lang="scss" scoped>
#admin {
  height: calc(100vh - 84px);
  width: 100%;
  // background-color: rgb(241, 241, 241);
  background-color: #f9f9f9;
  padding: 20px;

  .admin-title {
    width: 100%;
    height: 70px;
    background-color: rgb(255, 255, 255);
    box-sizing: border-box;
    border-bottom: 1px solid #0000002e;
    padding-left: 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;

    div {
      line-height: 60px;
    }
  }
  .admin-table {
    width: 100%;
    height: calc(100vh - 254px);
    background: #fff;
    display: flex;
    flex-direction: column;

    .admin-button {
      width: 100%;
      padding: 20px;

      // .input {
      //   display: flex;
      //   justify-content: space-between;

      //   .seach {
      //     display: flex;

      //     ::v-deep .el-input {
      //       width: 210px;
      //       border-top-right-radius: 0px !important;

      //       .el-input__inner {
      //         border-top-right-radius: 0px;
      //         border-bottom-right-radius: 0px;
      //       }
      //     }

      //     ::v-deep .el-button--primary {
      //       border-top-left-radius: 0px;
      //       border-bottom-left-radius: 0px;
      //     }
      //   }
      // }
    }
    .tabel {
      width: 100%;
      height: calc(100vh - 356px);
      background-color: rgb(255, 255, 255);
      padding-right: 20px;
      padding-left: 20px;
      padding-bottom: 5px;
    }

    .el-table_1_column_3 {
      display: flex;
      justify-content: center;
      flex-wrap: wrap;

      #text {
        color: #fff;
        background-color: #409eff;
        width: auto !important;
        padding: 1px 5px 1px 5px;
        margin: 1px 2px 1px 2px;
        border-radius: 6px;
      }
    }
  }
  .admin-page {
    display: block;
    width: 100%;
    margin-top: 30px;
    text-align: center;
  }
}

::v-deep .el-dialog {
  margin-top: 8vh !important;
  width: 35% !important;
  min-width: 480px !important;

  .el-dialog__footer {
    position: relative;

    .dialog-footer-left {
      position: absolute;
      left: 20px;

      .el-button {
        color: #409eff;
      }
    }
  }
}
</style>